<?php
/**
 * Created by PhpStorm.
 * User: xkq
 * Date: 2017/12/26 0031
 * Time: 20:45
 * 短信发送
 */
set_include_path(dirname(dirname(__FILE__)));
include_once("inc/init.php");
if (!session_id()) session_start();
define("TOKEN", "maid");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if ($echoStr) {
            //valid signature , option
            if ($this->checkSignature()) {
                echo $echoStr;
                exit;
            }
        } else {
            $this->responseMsg();
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments

        $postStr = file_get_contents("php://input");
        $postObj = json_decode($postStr, true);

        //进入会话事件回复
        if ($postObj['MsgType'] == 'event') {
            if ($postObj['Event'] == 'user_enter_tempsession') {
                $data['touser'] = $postObj['FromUserName'];
                $data['msgtype'] = "image";
                $media_id = $this->uploadImg();
                $data['image'] = ["media_id" => $media_id];
                $data = json_encode($data);
                $accessToken = getAccessToken();
                $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$accessToken";
                $result = httpPost($url, $data);
            }

        }
		
		//自动回复文本
		$str = "";

        //文本消息回复
        if ($postObj['MsgType'] == 'text') {
            $data['touser'] = $postObj['FromUserName'];
            $data['msgtype'] = "text";
            $content = urlencode($str);
            $data['text'] = ["content" => $content];
            $data = json_encode($data);
            $data = urldecode($data);
            $accessToken = getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$accessToken";
            $result = httpPost($url, $data);
        }

        //图片消息回复
        if ($postObj['MsgType'] == 'image') {
            $data['touser'] = $postObj['FromUserName'];
            $data['msgtype'] = "text";
            $content = urlencode($str);
            $data['text'] = ["content" => $content];
            $data = json_encode($data);
            $data = urldecode($data);
            $accessToken = getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$accessToken";
            $result = httpPost($url, $data);
    }

        //小程序卡片消息回复
        if ($postObj['MsgType'] == 'miniprogrampage') {
            $data['touser'] = $postObj['FromUserName'];
            $data['msgtype'] = "text";
            $content = urlencode($str);
            $data['text'] = ["content" => $content];
            $data = json_encode($data);
            $data = urldecode($data);
            $accessToken = getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$accessToken";
            $result = httpPost($url, $data);
        }


    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function uploadImg()
    {
        $accessToken = getAccessToken();
        $file_info = array(
            'filename' => '/maid/api/20171226.jpg',  //图片相对于网站根目录的路径
            'content-type' => 'image/jpg',  //文件类型
            'filelength' => '562500'         //图文大小
        );
        $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $accessToken . "&type=image";
        $real_path = "{$_SERVER['DOCUMENT_ROOT']}{$file_info['filename']}";
        $data = array("media" => "@{$real_path}", 'form-data' => $file_info);

        if (class_exists('\CURLFile')) {
            $data['media'] = new \CURLFile(realpath($real_path));
        } else {
            $data['media'] = '@'.realpath($real_path);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, FALSE);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        $return_data = json_decode($result,true);
        return $return_data['media_id'];
    }
}

?>

